<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">{{ $t("login.form.title") }}</div>
    <!-- <div class="login-form-sub-title">{{ $t('login.form.title') }}</div> -->
    <!-- <div class="login-form-error-msg">{{ errorMessage }}</div> -->
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="mobile"
        class="login-form-phone"
        :rules="[{ required: true, message: $t('login.form.phone.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input
          v-model="userInfo.mobile"
          :placeholder="$t('login.form.phone.placeholder')"
          allow-clear
        >
          <!-- <template #prefix>
            <icon-user />
          </template> -->
          <template #prefix> +86 </template>
          <!-- <template #prepend>
            +86
          </template> -->
        </a-input>
      </a-form-item>
      <a-form-item
        field="pwd"
        class="login-form-password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.pwd"
          :placeholder="$t('login.form.password.placeholder')"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword"
          >
            {{ $t("login.form.rememberPassword") }}
          </a-checkbox>
          <span class="login-form-forget-password" @click="handleUpdatePasswordClick">{{
            $t("login.form.forgetPassword")
          }}</span>
          <!-- <a-link class="login-form-forget-password">{{ $t('login.form.forgetPassword') }}</a-link> -->
        </div>
        <a-button
          type="primary"
          html-type="submit"
          class="login-form-submit-btn"
          long
          :loading="loading"
        >
          {{ $t("login.form.login") }}
        </a-button>
        <!-- <a-button type="text" long class="login-form-register-btn">
          {{ $t('login.form.register') }}
        </a-button> -->
      </a-space>
    </a-form>
    <!-- 修改密码弹窗 -->
    <Dialog
      :visible="dialogVisible"
      :title="'忘记密码'"
      :width="500"
      :maskClosable="false"
      :isForm="true"
      :okText="'确定'"
      @update:visible="handleVisible"
    >
      <template v-slot>
        <div class="dialog-body">
          <a-form :model="forgetForm" ref="formRef">
            <a-space direction="vertical" fill>
              <a-form-item
                field="mobile"
                label="账号"
                required
                :rules="[{ required: true, type: 'string', message: '账号不能为空' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <a-input
                  v-model="forgetForm.mobile"
                  :style="{ width: '272px', height: '32px' }"
                  placeholder="请输入您的账号"
                  allow-clear
                />
              </a-form-item>
              <a-form-item
                field="shortCode"
                label="密码验证码"
                required
                :rules="[
                  { required: true, type: 'string', message: '密码验证码不能为空' },
                ]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <a-input
                  v-model="forgetForm.shortCode"
                  :style="{ width: '272px', height: '32px' }"
                  placeholder="请输入您的密码验证码"
                  allow-clear
                />
              </a-form-item>
              <a-form-item
                field="newPwd"
                label="新密码"
                required
                :rules="[
                  { required: true, type: 'string', message: '新密码不能为空' },
                  { minLength: 6, message: '密码不能少于6位' },
                  {
                    match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                    message: '密码格式不正确',
                  },
                ]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <a-input-password
                  v-model="forgetForm.newPwd"
                  :style="{ width: '272px', height: '32px' }"
                  :max-length="16"
                  placeholder="请设置6-16位新密码"
                  allow-clear
                />
              </a-form-item>
              <a-form-item
                field="againPassword"
                label="确认新密码"
                required
                :rules="[
                  { required: true, type: 'string', message: '确认新密码不能为空' },
                  {
                    match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                    message: '密码格式不正确',
                  },
                ]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <a-input-password
                  v-model="forgetForm.againPassword"
                  :style="{ width: '272px', height: '32px' }"
                  :max-length="16"
                  placeholder="请再次输入您的新密码"
                  allow-clear
                />
              </a-form-item>
            </a-space>
          </a-form>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, inject } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Message } from "@arco-design/web-vue";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { useI18n } from "vue-i18n";
import md5 from "md5";
import { useStorage } from "@vueuse/core";
import { useUserStore } from "@/store";
import useAccount from "../hooks/useAccount";
import useLoading from "@/hooks/loading";
import usePermission from "@/hooks/permission";
import type { LoginData } from "@/api/user/user.d";
import Dialog from "@/components/dialog/index.vue";
import { appRoutes } from "@/router/routes";

const router = useRouter();
const { t } = useI18n();
const errorMessage = ref("");
const { loading, setLoading } = useLoading();
const userStore = useUserStore();
const Permission = usePermission();
const routes = inject<any>("secondRoute");
const loginConfig = useStorage("login-config", {
  rememberPassword: true,
  mobile: "admin", // 演示默认值
  pwd: "123456", // demo default value
});
const userInfo = reactive({
  mobile: loginConfig.value.mobile,
  pwd: loginConfig.value.pwd,
});

const handleSubmit = async ({
  errors,
  values,
}: {
  errors: Record<string, ValidatedError> | undefined;
  values: Record<string, any>;
}) => {
  if (loading.value) return;
  if (!errors) {
    setLoading(true);
    try {
      const loginData = {
        mobile: values.mobile,
        pwd: md5(values.pwd),
      };
      await userStore.login(loginData as LoginData);
      const { redirect, ...othersQuery } = router.currentRoute.value.query;
      // let current = "";
      // if (redirect && redirect !== "") {
      //   const curRoute = Permission.getPermissionCodeByName(routes, redirect);
      //   if (Permission.permissionRouter(curRoute)) {
      //     current = redirect as string;
      //   }
      //   if (current === "") {
      //     current = Permission.btnFindRoute(routes);
      //   }
      // } else {
      //   current = Permission.btnFindRoute(routes);
      // }
      const current = Permission.findFirstPermissionRoute(appRoutes, userStore.role);
      router.push({
        name: (redirect as string) || current?.name,
        query: {
          ...othersQuery,
        },
      });
      Message.success(t("login.form.login.success"));
      const { rememberPassword } = loginConfig.value;
      // const { username, password } = values;
      const { mobile, pwd } = values;
      // 实际生产环境需要进行加密存储。
      // The actual production environment requires encrypted storage.
      // loginConfig.value.username = rememberPassword ? username : '';
      // loginConfig.value.password = rememberPassword ? password : '';
      loginConfig.value.mobile = rememberPassword ? mobile : "";
      loginConfig.value.pwd = rememberPassword ? pwd : "";
    } catch (err) {
      errorMessage.value = (err as Error).message;
    } finally {
      setLoading(false);
    }
  }
};
const setRememberPassword: any = (value: boolean) => {
  loginConfig.value.rememberPassword = value;
};

const {
  dialogVisible,
  forgetForm,
  formRef,
  handleVisible,
  handleUpdatePasswordClick,
} = useAccount();
</script>

<style lang="less" scoped>
.login-form {
  padding: 0 32px;
  &-wrapper {
    width: 464px;
    background: rgba(229, 229, 229, 0.2);
    border-radius: 4px;
  }

  &-title {
    color: var(--color-white);
    font-weight: 500;
    font-size: 25px;
    line-height: 60px;
    background: rgba(229, 229, 229, 0.45);
    border-radius: 5px;
    margin-bottom: 100px;
    text-align: center;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-phone {
    margin-bottom: 50px;
  }
  &-password {
    margin-bottom: 20px;
    :deep(.arco-input-prefix) {
      width: 38.81px;
    }
  }
  &-phone,
  &-password {
    height: 50px;
    :deep(.arco-form-item-wrapper-col) {
      height: inherit;
      .arco-form-item-content-wrapper {
        height: inherit;
        .arco-form-item-content-flex {
          height: inherit;
          .arco-input-wrapper {
            height: inherit;
            background-color: transparent;
            border: 1px solid #fff;
            color: var(--color-white);
            .arco-input-prefix {
              color: var(--color-white);
            }
            .arco-input-clear-btn {
              color: var(--color-white);
            }
            .arco-input-suffix {
              display: none;
            }
            .arco-input:-internal-autofill-selected {
              background-color: transparent;
            }
          }
        }
      }
    }
    ::-webkit-input-placeholder {
      color: #fff;
    }
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
    color: var(--color-white);
    :deep(.arco-checkbox) {
      .arco-checkbox-icon {
        background-color: transparent;
        border: 1px solid #ccc;
      }
    }
    :deep(.arco-checkbox.arco-checkbox-checked) {
      .arco-checkbox-icon {
        background-color: #448e97;
        border-color: transparent;
      }
    }
  }

  &-forget-password {
    color: var(--color-white);
    text-decoration: underline;
    cursor: pointer;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }

  &-submit-btn {
    // margin-bottom: 40px;
    margin: 50px 0 40px;
    height: 50px;
  }
}
:deep(.arco-icon-hover:hover::before) {
  background-color: transparent;
}
:deep(.arco-checkbox > input[type="checkbox"]:focus + .arco-checkbox-icon-hover::before) {
  background-color: transparent;
}
:deep(.arco-checkbox:hover .arco-checkbox-icon-hover::before) {
  background-color: transparent;
}

:deep(.arco-checkbox-label) {
  color: var(--color-white);
}

:deep(.arco-form-item-label-col > .arco-form-item-label) {
  white-space: nowrap;
}
</style>
